import React, { Component } from 'react';
import { addBillList } from '../../../api'
class Index extends Component {
  state = {
    formData: {
      name: '',
      tip: '',
      type: '支出',
      price: '',
    }
  }
  handleChange(e) {
    const { formData } = this.state
    // 键名
    const type = e.target.name
    // 键值
    const value = e.target.value

    formData[type] = value

    this.setState({
      formData
    })
  }
  async handleSubmit() {
    const { formData } = this.state

    const resp = await addBillList(formData)

    const { code, mess } = resp.data
    
    if(code === 200) {
      alert(mess)
    } else {
      alert('很遗憾， 添加失败！！！')
    }

    Object.keys(formData).forEach(key => formData[key] = '')

    this.setState({
      formData,
    })
    
  }
  render() {
    const { formData: { name, tip, type, price } } = this.state
    return (
      <div>
        <form>
          <p>
            <b>账单名称</b>
            {/* 受控组件： 被 react state 控制 */}
            <input type="text" value={name} onChange={e => this.handleChange(e)} name="name"/>
          </p>
          <p>
            <b>账单备注</b>
            <textarea type="text" value={tip} onChange={e => this.handleChange(e)} name="tip"/>
          </p>
          <p>
            <b>账单类型</b>
            <select  id="" value={type} onChange={e => this.handleChange(e)} name="type">
              <option value="支出">支出</option>
              <option value="收入">收入</option>
            </select>
          </p>
          <p>
            <b>账单描述</b>
            <input type="text" value={price} onChange={e => this.handleChange(e)} name="price"/>
          </p>
          <button type="button" onClick={ () => this.handleSubmit() }>提交账单</button>
        </form>
      </div>
    );
  }
}

export default Index;
